package admin

import (
	"context"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/roleLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/businessCommonQuery"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminRoleIndex(ctx context.Context, pb *pbAdmin.AdminRoleIndexReq) (*pbAdmin.AdminRoleIndexResp, error) {
	where, bindValue, limit, order, e := businessCommonQuery.BuildByBusinessCommonQuery(pb.BusinessCommonQuery)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	authRoleIds := []interface{}{}

	if pb.OperaterId != 0 {
		roleIds := adminLogic.GetChildrenRoleIds(ctx, pb.OperaterId, true)
		where += " and id in (?)"
		bindValue = append(bindValue, roleIds)
		authRoleIds = adminLogic.GetRoleIdsByAdminId(ctx, pb.OperaterId)
	}

	Db := database.Db.GetDefaultDb(ctx)

	total, dbErr := Db.Find(fmt.Sprintf("select count(*) total from admin_role where 1=1 %s", where), bindValue...)
	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	rows, dbErr := Db.Query(fmt.Sprintf("select * from admin_role where 1=1 %s %s %s", where, order, limit), bindValue...)
	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	resp := &pbAdmin.AdminRoleIndexResp{
		Rows:  make([]*pbAdmin.AdminRole, len(rows)),
		Total: total["total"].(int64),
	}

	list := roleLogic.List()
	ids := utils.ArrayColumn(rows, "id")
	for i, row := range rows {
		businessCommonQuery.ListFormat(list, row)
		resp.Rows[i] = &pbAdmin.AdminRole{
			Id:          row["id"].(int64),
			Pid:         row["pid"].(int64),
			Name:        row["name"].(string),
			Status:      int32(row["status"].(int64)),
			UpdateTime:  row["update_time"].(string),
			CreateTime:  row["create_time"].(string),
			Disabled:    0,
			PidOriginal: row["pid"].(int64),
			StatusText:  row["status_text"].(string),
		}

		if utils.InArray(row["id"].(int64), authRoleIds) {
			resp.Rows[i].Disabled = 1
		}
		if !utils.InArray(row["pid"].(int64), ids) {
			resp.Rows[i].Pid = 0
		}
	}

	return resp, nil
}
